package emulator.hardware.io.peripherals.iec;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class IecSimFilePrinter implements IecSimDevice 
{
	static Logger logger = LogManager.getLogger(IecSimFilePrinter.class.getName());
	private IecSim _iecSim = null;
	private FileOutputStream _outputStream = null;
	private File _outFile = null;
	
	public IecSimFilePrinter(String fileName)
	{
		logger.info("Printing to file "+fileName);
		_outFile = new File(fileName);
		try {
			_outFile.createNewFile();
			if (!_outFile.canWrite())
				logger.warn("Cannot write to file "+fileName);
		} catch (IOException ex) {
			logger.error("File does not exists and cannot create file "+fileName, ex);
			_outFile = null;
		}
	}
	
	@Override
	public void setIecSim(IecSim iecSim) {
		_iecSim  = iecSim;
	}

	@Override
	public void processCommand(ByteBuffer data)
	{
		processData(data);
	}

	@Override
	public void processData(ByteBuffer data)
	{
		if (_outputStream != null)
		{
			try {
				_outputStream.getChannel().write(data);
			} catch (IOException ex) {
				logger.error("Cannot write data to file " + _outFile.getName(), ex);
			}
		}
	}

	@Override
	public void unlisten() {
		try {
			_outputStream.close();
		} catch (IOException ex) {
			logger.error("Cannot close file "+_outFile.getName(), ex);
		}
		_outputStream = null;
	}

	@Override
	public void listen() {
		logger.entry();
		try {
			_outputStream = new FileOutputStream(_outFile, true /* append */);
			_iecSim.initReceive(this);
		} catch (FileNotFoundException ex) {
			logger.error("Cannot open file "+_outFile.getName(), ex);
		}
	}

	@Override
	public void talk() {
		logger.warn("Printers can't talk!");
	}

	@Override
	public void untalk() {
		/* NOP */
	}

	@Override
	public int read() {
		logger.warn("Reading from printer not supported!");
		return -1;
	}

	@Override
	public void rewind(int offset) {
		/* NOP */
	}
}
